package com.hooper.login.aop;

import com.hooper.login.anno.TokenIgnore;
import com.hooper.login.constant.CommonConstant;
import com.hooper.login.entity.*;
import com.hooper.login.exception.BusinessException;
import com.hooper.login.util.JWTUtil;
import com.hooper.login.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/12/28/12:29
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = ((HandlerMethod) handler);
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(TokenIgnore.class)) {
                return true;
            }
        }
        String token = request.getHeader(CommonConstant.TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("not login or token expired, please login");
        }
        UserDto userDto = JWTUtil.getUserVo(token);
        UserHolder.setUser(userDto);
        log.info("当前用户：" + userDto.getName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.remove();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
